#!/bin/bash
#
# Copyright (C) 2012 Christian Babeux <christian.babeux@efficios.com>
#
# SPDX-License-Identifier: GPL-2.0-only
#

TEST_DESC="Filtering - Unsupported operators"

CURDIR=$(dirname $0)/
TESTDIR=$CURDIR/../../..
SESSION_NAME="filter-unsupported-ops"
EVENT_NAME="bogus"
ENABLE_EVENT_STDERR="/tmp/unsupported-ops-enable"
TRACE_PATH=$(mktemp -d -t tmp.test_filtering_unsupported_ops_trace_path.XXXXXX)
NUM_GLOBAL_TESTS=2
NUM_UST_TESTS=20
NUM_KERNEL_TESTS=20
NUM_TESTS=$(($NUM_UST_TESTS+$NUM_KERNEL_TESTS+$NUM_GLOBAL_TESTS))

source $TESTDIR/utils/utils.sh

function enable_lttng_event_filter_unsupported
{
	domain="$1"
	sess_name="$2"
	event_name="$3"
	filter="$4"

	enable_cmd="$TESTDIR/../src/bin/lttng/$LTTNG_BIN enable-event"
	$enable_cmd $event_name -s $sess_name $domain --filter "$filter" 2> $ENABLE_EVENT_STDERR 1> /dev/null

	# Enable must fail
	if [ $? -eq 0 ]; then
		fail "Enable lttng event with filtering and unsupported operator"
		return 1
	else
		pass "Enable lttng event with filtering and unsupported operator"
		return 0
	fi
}

function test_unsupported_op
{
	domain="$1"
	test_op_str="$2"
	test_op_tkn="$3"

	diag "Test filter expression with unsupported operator $test_op_str ($test_op_tkn)"

	# Create session
	create_lttng_session_ok $SESSION_NAME $TRACE_PATH

	# Create filter
	if [ "$test_op_str" == "UNARY_BIN_NOT" ]; then
		TEST_FILTER="${test_op_tkn}1"
	else
		TEST_FILTER="intfield $test_op_tkn 1"
	fi

	# Apply filter
	enable_lttng_event_filter_unsupported $domain $SESSION_NAME $EVENT_NAME "$TEST_FILTER"

	# Test stderr for unsupported operator

	grep -i -q "not[[:space:]]\+supported" $ENABLE_EVENT_STDERR

	if [ $? -eq 1 ]; then
		fail "Unsupported operator test $test_op_str ($test_op_tkn)"
		return 1
	else
		pass "Unsupported operator test $test_op_str ($test_op_tkn)"
	fi

	# Destroy session
	destroy_lttng_session_ok $SESSION_NAME
	return 0
}

plan_tests $NUM_TESTS

print_test_banner "$TEST_DESC"

# Unsupported operators
OP_STR=("MUL" "DIV" "MOD" "PLUS" "MINUS")

OP_TKN=("*" "/" "%" "+" "-")

OP_COUNT=${#OP_STR[@]}

start_lttng_sessiond

diag "Test UST unsupported filter operations"

i=0
while [ "$i" -lt "$OP_COUNT" ]; do
	test_unsupported_op -u "${OP_STR[$i]}" "${OP_TKN[$i]}"

	if [ $? -eq 1 ]; then
		exit 1
	fi

	let "i++"
done

check_skip_kernel_test $NUM_KERNEL_TESTS "Skipping kernel unsupported filter operations tests." ||
{
	diag "Test kernel unsupported filter operations"

	i=0
	while [ "$i" -lt "$OP_COUNT" ]; do
		test_unsupported_op -k "${OP_STR[$i]}" "${OP_TKN[$i]}"

		if [ $? -eq 1 ]; then
			exit 1
		fi

		let "i++"
	done
}

stop_lttng_sessiond

# Cleanup
rm -f $ENABLE_EVENT_STDERR
rm -rf $TRACE_PATH
